package com.service.firstapp.service;

import com.huawei.paas.cse.tcc.annotation.TccTransaction;
import com.service.firstapp.bean.PeopleInfo;
import com.service.firstapp.bean.PeopleInfoRowMapper;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.ws.rs.core.MediaType;

/**
 * Created by wjh on 2018/3/27.
 */
@RpcSchema(schemaId = "peopleInfoService")
@RequestMapping(path = "/thirdapp/info_service", produces = MediaType.APPLICATION_JSON)
public class PeopleInfoServiceImpl implements PeopleInfoService {

    private static final Logger logger = LoggerFactory.getLogger(PeopleInfoServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

       /**
     * 新增peopleinfo
     * @param people
     */
    @TccTransaction(confirmMethod = "confirm", cancelMethod = "cancel")
    @RequestMapping(method = RequestMethod.POST)
    public PeopleInfo addPeopleInfo(@RequestBody PeopleInfo people) {
        String sql = "insert into people_info values(?,?,?,?)";
        jdbcTemplate.update(sql, people.getPeopleId(), people.getSex(), people.getHeight(), people.getStatus());
        return people;
    }

    public void confirm(PeopleInfo peopleInfo) {
        logger.info("==========confirm==========");
        //confirm
        peopleInfo.setStatus(1);
        updatePeopleInfo(peopleInfo);
    }

    public void cancel(PeopleInfo peopleInfo) {
        logger.info("==========cancel==========");
        //cancel
        peopleInfo.setStatus(2);
        updatePeopleInfo(peopleInfo);
    }

    /**
     * 更新peopleInfo
     * @param people
     */
    @RequestMapping(value="/{people_id}",method = RequestMethod.PUT)
    public PeopleInfo updatePeopleInfo(@RequestBody PeopleInfo people) {
         String sql = "update people_info set status = " + people.getStatus() + " where people_id = ?";
        jdbcTemplate.update(sql, people.getPeopleId());
        return people;
    }

    /**
     * 根据peopleId查询peopleInfo
     * @param peopleId
     * @return
     */
    @RequestMapping(value = "/{people_id}", method = RequestMethod.GET)
    @Override
    public PeopleInfo getPeopleInfoById(@PathVariable(value = "people_id") Integer peopleId) {
        String sql = "select * from people_info where people_id = ? ";
        PeopleInfo peopleInfo = jdbcTemplate.queryForObject(sql, new PeopleInfoRowMapper(), peopleId);
        return peopleInfo;
    }

}
